import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'LoginPage',
    component: () => import('@/pages/login/LoginPage.vue')
  },
  {
    path: '/register',
    name: 'RegisterPage',
    component: () => import('@/pages/register/RegisterPage.vue')
  },
  {
    path: '/teacher',
    name: 'TeacherLayout',
    component: () => import('@/pages/teacher/Layout.vue'),
    meta: { requiresAuth: true, role: 'teacher' },
    children: [
      {
        path: 'activities',
        name: 'TeacherActivities',
        component: () => import('@/pages/teacher/Activities.vue')
      },
      {
        path: 'statistics',
        name: 'TeacherStatistics',
        component: () => import('@/pages/teacher/Statistics.vue')
      },
      {
        path: 'qrcode',
        name: 'QRCodeSign',
        component: () => import('@/components/QRCodeSign.vue')
      }
    ]
  },
  {
    path: '/student',
    component: () => import('@/pages/student/Layout.vue'),
    meta: { requiresAuth: true, role: 'student' },
    children: [
      {
        path: '',
        name: 'StudentLayout',
        redirect: '/student/sign-in'
      },
      {
        path: 'profile',
        name: 'StudentProfile',
        component: () => import('@/pages/student/Profile.vue')
      },
      {
        path: 'join-teacher',
        name: 'JoinTeacher',
        component: () => import('@/pages/student/JoinTeacher.vue')
      },
      {
        path: 'activities',
        name: 'StudentActivities',
        component: () => import('@/pages/student/Activities.vue')
      },
      {
        path: 'records',
        name: 'SignRecords',
        component: () => import('@/pages/student/Records.vue')
      },
      {
        path: 'sign-in',
        name: 'StudentSignIn',
        component: () => import('@/pages/student/SignIn.vue')
      }
    ]
  },
  {
    path: '/qrcode-sign',
    name: 'QRCodeSign',
    component: () => import('@/components/QRCodeSign.vue'),
    meta: { requiresAuth: true, role: 'teacher' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')

  // 不需要认证的路由
  const publicRoutes = ['/login', '/register']
  
  if (publicRoutes.includes(to.path)) {
    next()
    return
  }

  // 需要认证但没有 token
  if (!token) {
    next('/login')
    return
  }

  // 检查角色权限
  if (to.meta.role && to.meta.role !== userRole) {
    next('/login')
    return
  }

  next()
})

export default router 